package com.doys.myfirstapp;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.*;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.*;
import android.view.ViewTreeObserver.OnWindowFocusChangeListener;
import android.webkit.*;
import android.widget.ProgressBar;

import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private boolean isInput;
    WebView webView;
    ProgressBar pb1;

    // -- Activity events -----------------------------------------------------
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogToFile.i("test","test");

        //监听返回和home按键
//        ListenRecentAndHome();

        initWebView();

//        loadUrl("");

        onKeyBoardListener();
    }

    //写数据
    public void writeFile(String fileName,String writestr)  {
        try{
            FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);
            byte [] bytes = writestr.getBytes();
            fout.write(bytes);
            fout.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();

            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
//            webView.goBack();
//            return true;
            Log.d("DeviceKeyMonitor", "按了返回键1111");
        }
        else {

        }
        return super.onKeyDown(keyCode, event);
    }

    private BroadcastReceiver recentReceiver;
    private static final String SYSTEM_REASON = "reason";
    private static final String SYSTEM_HOME_KEY = "homekey";
    private static final String SYSTEM_HOME_RECENT_APPS = "recentapps";
    public void ListenRecentAndHome(){

        recentReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null && intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){
                    String reason = intent.getStringExtra(SYSTEM_REASON);
                    if (!TextUtils.isEmpty(reason)){
                        if (SYSTEM_HOME_KEY.equals(reason)){
                            onHomeClick();
                        } else if (SYSTEM_HOME_RECENT_APPS.equals(reason)){
                            onRecentClick();
                        }
                    }
                }
            }
        };
        this.registerReceiver(recentReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
    }

    public void onHomeClick() {
        //Toast.makeText(this,"点击了Home键",Toast.LENGTH_LONG).show();
        Log.d("DeviceKeyMonitor", "按了Home键");
    }

    public void onRecentClick() {
        Log.d("DeviceKeyMonitor", "按了返回键");
        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.moveTaskToFront(getTaskId(), 0);
    }



    private void onKeyBoardListener() {
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                Log.e("软键盘", "键盘显示 高度" + height);
                isInput = true;
            }

            @Override
            public void keyBoardHide(int height) {
                Log.e("软键盘", "键盘隐藏 高度" + height);
                isInput = false;
            }
        });
    }
    // -- WebView Process ----------------------------------------------------- s
    private void initWebView() {
        webView = findViewById(R.id.webView1);
        pb1 = findViewById(R.id.progressBar1);

        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptEnabled(true);                         // -- 支持Javascript交互 --
        webSettings.setDefaultTextEncodingName("utf-8");                // -- 设置编码格式 --
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);     // -- 支持通过JS弹出对话框 --


        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // -- 打开网页时不调用系统浏览器 --
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
            @Override
            public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                if (isInput) {
                    // -- 软键盘已调起 --
                    return super.shouldOverrideKeyEvent(view, event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                    return super.shouldOverrideKeyEvent(view, event);
                }
                if (event.getAction() == KeyEvent.ACTION_UP) {
                    return true;
                }

                // -- 截获处理 --
                doScan(event);
                return true;
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress < 100) {
                    pb1.setVisibility(View.VISIBLE);
                    pb1.setProgress(newProgress);
                }
                else if (newProgress == 100) {
                    pb1.setVisibility(View.GONE);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("系统信息...")
                        .setMessage(message)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.confirm();
                            }
                        })
                        .setCancelable(false)
                        .show();
                return true;
            }
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("系统信息...")
                        .setMessage(message)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.confirm();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.cancel();
                            }
                        })
                        .setCancelable(false)
                        .show();
                return true;
            }
        });

        pb1.setVisibility(View.GONE);
        pb1.setMax(100);
    }
    private void loadUrl(String urlDefault) {
        //webView.loadUrl("http://192.168.2.66/DoYsUI/index.html");
        //webView.loadUrl("http://127.0.0.1/DoYsUI/index.html");
        //webView.loadUrl("http://www.baidu.com/");
        //webView.loadUrl("http://192.168.2.66:5556");
        //webView.loadUrl("http://192.168.2.66:7000/xpas/project/g_spd/html/pda/dist/mobile.html#/login");

        //webView.loadUrl("http://192.168.2.66:7000/xpas/project/g_spd/html/app_login.html");

        webView.loadUrl("file:///android_asset/index.html");
    }

    // -- do scan -------------------------------------------------------------
    private void doScan(KeyEvent event) {
        final String scanString;
        // ------------------------------------------------
        try {
            scanString = ScanHelper.analysisKeyEvent(event);
            if (scanString != null) {
                System.out.println(scanString);
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        if (!scanString.equals("")) {
                            webView.loadUrl("javascript:androidCallJS({\"code\": \"" + scanString.toUpperCase() + "\"})");
                        }
                        else {
                            webView.loadUrl("javascript:androidCallJS({\"code\": \"" + "__ENTER__" + "\"})");
                        }
                    }
                });
            }
            else {
                // -- 尚未收到回车符，暂存在缓冲区 --
            }
        } catch (Exception e) {
            MessageBox.getInfoBuilder(this, e.getMessage()).show();
            e.printStackTrace();
        }
    }


    // -- 备用代码，通过Activity拦截，暂时不用，改为上面的通过WebView拦截 ---------------
    // -- @Override
  /*  public boolean dispatchKeyEvent___(KeyEvent event) {
        if (isInput) {
            return super.dispatchKeyEvent(event);
        }

        final String scanString;
        int eventKeyCode = event.getKeyCode();
        // ------------------------------------------------
        try {
            //MessageBox.getInfoBuilder(this, "收到：" + eventKeyCode).show();
            if (eventKeyCode == KeyEvent.KEYCODE_BACK) {
                return super.dispatchKeyEvent(event);
            }
            if (event.getAction() == KeyEvent.ACTION_UP) {
                return true;
            }

            scanString = ScanHelper.analysisKeyEvent(event);
            if (scanString != null) {
                if (scanString != "") {
                    System.out.println(scanString);
                    webView.post(new Runnable() {
                        @Override
                        public void run() {
                            webView.loadUrl("javascript:androidCallJS({\"code\": \"" + scanString.toUpperCase() + "\"})");
                        }
                    });
                }
                else {
                    // -- TODO: 暂不处理，扫码一个独立的回车符 --
                    System.out.println("扫码一个独立的回车符");
                    webView.post(new Runnable() {
                        @Override
                        public void run() {
                            webView.loadUrl("javascript:androidCallJS({\"code\": \"" + "ENTER" + "\"})");
                        }
                    });
                }
            }
        } catch (Exception e) {
            MessageBox.getInfoBuilder(this, e.getMessage()).show();
            e.printStackTrace();
        }
        return true;
    }*/

}
